import * as signalR from '@microsoft/signalr'
import { token } from '@/storage'

const withUrl = '/chat'
const connection = new signalR.HubConnectionBuilder()
  .withUrl(withUrl, { accessTokenFactory: () => token.value || '' })
  // .withHubProtocol(new signalRMsgPack.MessagePackHubProtocol())
  // .configureLogging(signalR.LogLevel.Information) // 打印连接日志
  .configureLogging(3) // 不打印
  .withAutomaticReconnect({
    nextRetryDelayInMilliseconds: (retryContext) => {
      // store.dispatch('setSignalrState', false)
      if (retryContext.elapsedMilliseconds < 120000) {
        // If we've been reconnecting for less than 120 seconds so far,
        // wait between 0 and 10 seconds before the next reconnect attempt.
        return 5000
      } else {
        // If we've been reconnecting for more than 120 seconds so far, stop reconnecting.
        return null
      }
    }
  })
  .build()

connection.onreconnected((connectionId) => {
  console.log('Successful reconnection =>', connectionId)
})
connection.onreconnecting((err) => {
  console.log('error reconnection =>', err)
})
export default connection
